﻿using Basefr.Core.Entities;
using System.Collections.Generic;
using System.Linq;

namespace Basefr.Core.Extensions
{
    public static class SelfReferenceEntityExtensions
    {
        public static List<T> OrderByLevel<T>(this ICollection<T> list) where T : EntityBase, ISelfReference<T>
        {
            var result = new List<T>();

            void FillLevelEntities(T item)
            {
                result.Add(item);

                list.Where(p => p.ParentId == item.Id).OrderBy(p => p.Id).ToList().ForEach(FillLevelEntities);
            }

            list.Where(p => !p.ParentId.HasValue || list.All(l => l.Id != p.ParentId)).OrderBy(p => p.Id).ToList().ForEach(FillLevelEntities);

            return result;
        }
    }
}
